//
//  BWPhotos.m
//  ShortVideo
//
//  Created by 侯歌 on 2022/3/8.
//

#import "BWPhotos.h"
#import <Photos/Photos.h>
#import "AuthorizationUtil.h"

@implementation BWPhotos

/** 创建自定义相册 */
+ (void)isExistFolder:(NSString * _Nonnull)folderName
        andBackaction:(void(^ _Nullable)(PHAssetCollection * _Nullable assetCollection))backAction {
    
    __block BOOL isExists = NO;
    
    //首先获取用户手动创建相册的集合
    PHFetchResult *collectonResuts = [PHCollectionList fetchTopLevelUserCollectionsWithOptions:nil];
    
    //对获取到集合进行遍历
    [collectonResuts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        PHAssetCollection *assetCollection = obj;
        //folderName是我们写入照片的相册
        if ([assetCollection.localizedTitle isEqualToString:folderName])  {
            isExists = YES;
            
            if (backAction) backAction(assetCollection);
        }
    }];
    
    if (!isExists) {
        if (backAction) backAction(nil);
    }
}

+ (void)createFolder:(NSString *_Nonnull)folderName
       andBackaction:(void(^ _Nullable)(PHAssetCollection *_Nullable assetCollection))backAction {
    // 先检查相册权限
    [AuthorizationUtil checkPhotoLibraryAuthorization:^{
        [self isExistFolder:folderName
              andBackaction:^(PHAssetCollection * _Nullable assetCollection) {
            //存在
            if (assetCollection) {
                if (backAction) backAction(assetCollection);
            }
            //不存在
            else{
                [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                    //添加HUD文件夹
                    [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:folderName];
                    
                } completionHandler:^(BOOL success, NSError * _Nullable error) {
                    if (success) {
                        NSLog(@"创建相册文件夹成功!");
                        
                        [self isExistFolder:folderName
                              andBackaction:^(PHAssetCollection * _Nullable assetCollection) {
                            if (backAction) backAction(assetCollection);
                        }];
                    } else {
                        NSLog(@"创建相册文件夹失败:%@", error);
                        if (backAction) backAction(nil);
                    }
                }];
            }
        }];
    }];
}

/// 保存图片到相册
+ (void)saveImageToAlbum:(UIImage *)image {
    //保存图片
    [self createFolder:K_APP_NAME
         andBackaction:^(PHAssetCollection *assetCollection) {
        NSLog(@"assetCollection:%@",assetCollection);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD show];
            [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                //请求创建一个Asset
                PHAssetChangeRequest *assetRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
                
                //请求编辑相册
                PHAssetCollectionChangeRequest *collectonRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
                
                //为Asset创建一个占位符，放到相册编辑请求中
                PHObjectPlaceholder *placeHolder = [assetRequest placeholderForCreatedAsset];
                
                //相册中添加图片
                [collectonRequest addAssets:@[placeHolder]];
                
            } completionHandler:^(BOOL success, NSError *error) {
                if (success) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [SVProgressHUD showSuccessWithStatus:@"已保存到系统相册"];
                    });
                    
                } else {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
                    });
                }
            }];
        });
    }];
}

/// 保存多张图片到相册
+ (void)saveImagesToAlbum:(NSArray *)imageArray {
    //保存图片
    [self createFolder:K_APP_NAME
         andBackaction:^(PHAssetCollection *assetCollection) {
        NSLog(@"assetCollection:%@",assetCollection);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD show];
            [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                NSMutableArray *tempArray = [NSMutableArray array];
                
                //请求编辑相册
                PHAssetCollectionChangeRequest *collectonRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
                
                for (int i = 0; i < imageArray.count; i++) {
                    UIImage *image = imageArray[i];
                    //请求创建一个Asset
                    PHAssetChangeRequest *assetRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
                    
                    //为Asset创建一个占位符，放到相册编辑请求中
                    PHObjectPlaceholder *placeHolder = [assetRequest placeholderForCreatedAsset];
                    [tempArray addObject:placeHolder];
                }
                
                //相册中添加图片
                [collectonRequest addAssets:tempArray];
                
            } completionHandler:^(BOOL success, NSError *error) {
                if (success) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [SVProgressHUD showSuccessWithStatus:@"已保存到系统相册"];
                    });
                    
                } else {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
                    });
                }
            }];
        });
    }];
}

/// 保存视频到相册
/// videoPath为视频下载到本地之后的本地路径
+ (void)saveVideoToAlbum:(NSString *)videoPath {
    
    __weak typeof(self) weakSelf = self;
    [self createFolder:K_APP_NAME
         andBackaction:^(PHAssetCollection *assetCollection) {
             NSLog(@"assetCollection:%@",assetCollection);
             
             dispatch_async(dispatch_get_main_queue(), ^{
                 [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                     //请求创建一个Asset
                     PHAssetChangeRequest *assetRequest = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:[NSURL URLWithString:videoPath]];
                     
                     //请求编辑相册
                     PHAssetCollectionChangeRequest *collectonRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
                     
                     //为Asset创建一个占位符，放到相册编辑请求中
                     PHObjectPlaceholder *placeHolder = [assetRequest placeholderForCreatedAsset];
                     
                     //相册中添加视频
                     [collectonRequest addAssets:@[placeHolder]];
                     
                 } completionHandler:^(BOOL success, NSError *error) {
                     if (success) {
                         NSLog(@"保存视频成功!");
                         
                         dispatch_async(dispatch_get_main_queue(), ^{
                             [SVProgressHUD showSuccessWithStatus:@"视频下载成功，已保存到系统相册"];
                             
                            //刷新UI
                            //...
                         });
                         
                     } else {
                         NSLog(@"保存视频失败:%@", error);
                         
                         dispatch_async(dispatch_get_main_queue(), ^{
                             [SVProgressHUD showErrorWithStatus:error.localizedDescription];
                         });
                     }
                 }];
             });
    }];
}
@end
